package com.pearl.security.multiloginreject.demo.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.Platform;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.pearl.security.multiloginreject.demo.content.PearlUserDetails;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author TD
 * @version 1.0
 * @date 2024/5/14
 */
public class LoginUtils {

    /**
     * 获取登录设备，也可以从登录参数中传过来
     */
    public static String parseDevice(HttpServletRequest request) {
        // 通过 User-Agent 判断
        UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        Platform platform = userAgent.getPlatform();
        if (!platform.isMobile()) {
            return "PC";
        } else {
            // 还可以进一步细分，不同系统的移动端允许登录
            boolean android = platform.isAndroid();
            boolean iPad = platform.isIPad();
            boolean ios = platform.isIos();
            return "MOBILE";
        }
        // 通过请求传递
        //String device = request.getHeader("Login-Device");
    }

    /**
     * 获取登录设备，从认证信息中获取（注意：其他登录方式需要兼容）
     */
    public static String parseDevice(Object principal) {
        return parsePrincipal(principal).getDevice();
    }

    /**
     * 获取认证用户的ID（注意：其他登录方式需要兼容）
     */
    public static String parseUserId(Authentication authentication) {
        return parsePrincipal(authentication.getPrincipal()).getUserId();
    }

    public static String parseUserId(Object principal) {
        return parsePrincipal(principal).getUserId();
    }

    private static PearlUserDetails parsePrincipal(Object principal) {
        if (ObjectUtil.isNotNull(principal)) {
            if (principal instanceof PearlUserDetails) {
                return (PearlUserDetails) principal;
            }
        }
        return null;
    }

    /**
     * 获取当前登录用户的标识 eg: PC:123456
     *
     * @param principal com.pearl.security.multiloginreject.demo.content.PearlUserDetails
     * @return key
     */
    public static  String getKey(Object principal) {
        return LoginUtils.parseDevice(principal) + StrUtil.COLON + LoginUtils.parseUserId(principal);
    }

    /**
     * 获取当前登录用户的标识 eg: PC:123456
     *
     * @param principal com.pearl.security.multiloginreject.demo.content.PearlUserDetails
     * @return key
     */
    public static String getKey(Authentication authentication) {
        return LoginUtils.parseDevice(authentication.getPrincipal()) + StrUtil.COLON + LoginUtils.parseUserId(authentication.getPrincipal());
    }
}
